package cn.fsd.service.impl;

import cn.fsd.domain.*;
import cn.fsd.feignclient.DispatchFeignClient;
import cn.fsd.mapper.*;
import cn.fsd.query.finance.StationQuery;
import cn.fsd.service.StationService;
import cn.fsd.vo.CourierBean;
import cn.fsd.vo.StationBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class StationServiceImpl implements StationService {

    @Autowired
    CourierMapper courierMapper;

    @Autowired
    TaskMapper taskMapper;

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    Customer_addressMapper customer_addressMapper;

    @Autowired
    StationMapper stationMapper;

    @Autowired
    DispatchFeignClient dispatchFeignClient;

    @Override
    public StationBean getSettlement(StationQuery stationQuery) {

        //待返回的最终结果
        StationBean stationBean = new StationBean();
        //待返回的快递员列表
        List<CourierBean> courierBeanList = new ArrayList<>();
        //从数据库获取到的快递员列表，*****此时id为station_id
        List<Courier> courierList = courierMapper.selectByStation(stationQuery.getId());

        int total_near_delivery = 0;//近距离配送单总数
        int total_far_delivery = 0;//远距离配送单总数
//        int total_delivery = 0;//配送单总数
        double total_income = 0;//配送费总收入
        double total_outcome = 0;//快递员总开支
//        double total_profit = 0;//总盈亏
        double all_delivery_distance = 0;//配送总距离

        for (int i = 0; i < courierList.size(); i++) {
            //遍历到的当前快递员
            Courier cur_courier = courierList.get(i);
//            System.out.println("*****当前快递员："+cur_courier.getCourier_name());
            //待填充的快递员对象
            CourierBean courierBean = new CourierBean();
            //填充快递员的基本信息
            courierBean.setCourier_id(cur_courier.getCourier_id());
            courierBean.setCourier_name(cur_courier.getCourier_name());
            courierBean.setCourier_phone(cur_courier.getCourier_phone());

            int near_delivery = 0;//近距离配送单数（<=5km）
            int far_delivery = 0;//远距离配送单数（>5km）
            double sum_fee = 0;//配送收费
            double courier_salary = 0;//快递员薪资

            //将id设置为courier_id，用于在数据库查询
            stationQuery.setId(cur_courier.getCourier_id());
            //从数据库获取到的配送单列表
            List<Task> taskList = taskMapper.selectByQuery(stationQuery);

            for (int j = 0; j < taskList.size(); j++) {
                //遍历到的当前配送单
                Task cur_task = taskList.get(j);
//                System.out.println("***********当前配送（任务）单号："+cur_task.getTask_id());
                //获取收货地址
                Order order = orderMapper.selectByPrimaryKey(cur_task.getOrder_id());
                //注意地址中存在的"/"要去掉，否则会被当作路径中的"/"
                String delivery_address = customer_addressMapper.selectByPrimaryKey(order.getCustomer_id(), order.getAddress_choice()).getReceiver_address().replace("/","");
                double[] deliveryLocationPoint = dispatchFeignClient.getGeo(delivery_address).getData();
//                System.out.println("***********收货人地址："+delivery_address);
                //获取分站地址
                String station_address = stationMapper.selectByPrimaryKey(cur_task.getStation_id()).getStation_place().replace("/","");
                double[] stationLocationPoint = dispatchFeignClient.getGeo(station_address).getData();
//                System.out.println("***********分站地址："+station_address);
                //计算收货地址和分站距离，单位为米
                double[] distenceAndTime = dispatchFeignClient.getDistenceAndTime(String.valueOf(deliveryLocationPoint[1]) + "," + String.valueOf(deliveryLocationPoint[0]), String.valueOf(stationLocationPoint[1]) + "," + String.valueOf(stationLocationPoint[0])).getData();
                double delivery_distence = distenceAndTime[0]/1000;
//                System.out.println("***********距离："+delivery_distence);
                //根据距离计算配送费：<=5km的10元，>5km的每加1公里2元，不足1公里按1公里计算（这里距离需要向上取整）
                double delivery_fee = 0;
                if(delivery_distence<=5) {
                    delivery_fee = 10;
                    near_delivery++;
                }
                else {
                    delivery_fee = 10+(Math.ceil(delivery_distence)-5)*2;
                    far_delivery++;
                }
//                System.out.println("***********配送费："+delivery_fee);
                //计算快递员抽成：配送费的20%
                double courier_commission = 0.2*delivery_fee;
//                System.out.println("***********快递员抽成："+courier_commission);

                //计算快递员的工作量信息
                sum_fee += delivery_fee;
                courier_salary += courier_commission;
                //计算配送总距离
                all_delivery_distance += delivery_distence;
            }

            //计算返回结果中的几个统计值
            total_near_delivery += near_delivery;
            total_far_delivery += far_delivery;
//            System.out.println("*****当前配送单总数："+(total_near_delivery+total_far_delivery));
//            total_delivery += (near_delivery+far_delivery);
            total_income += sum_fee;
            total_outcome += courier_salary;
//            System.out.println("*****当前总盈亏："+(total_income-total_outcome));
            //填充快递员的工作量信息
            courierBean.setNear_delivery(near_delivery);
            courierBean.setFar_delivery(far_delivery);
            courierBean.setSum_fee(sum_fee);
            courierBean.setCourier_salary(courier_salary);
            //加入到待返回的快递员列表中
            courierBeanList.add(courierBean);
        }
//        total_profit = total_income-total_outcome;

        //填充返回结果的数据
        stationBean.setTotal_courier(courierList.size());
        stationBean.setTotal_near_delivery(total_near_delivery);
        stationBean.setTotal_far_delivery(total_far_delivery);
        stationBean.setTotal_delivery(total_near_delivery+total_far_delivery);
        stationBean.setTotal_income(total_income);
        stationBean.setTotal_outcome(total_outcome);
        stationBean.setTotal_profit(total_income-total_outcome);
        stationBean.setAll_delivery_distance(all_delivery_distance);
        stationBean.setCourierlist(courierBeanList);

        return stationBean;

    }
}
